package com.pactera.madp.cp.controller.oms.prod;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.cp.api.dto.prod.ProdDto;
import com.pactera.madp.cp.api.entity.prod.ProdEntity;
import com.pactera.madp.cp.api.vo.prod.ProdGroupVo;
import com.pactera.madp.cp.common.enums.ProductGroupEnum;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.ProdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 华融湘江产品审批管理
 *
 * @author HuHao
 * @date 2022/6/10 14:55
 */
@RestController
@AllArgsConstructor
@RequestMapping("/prod-approval")
@Api(value = "prod-approval", tags = "产品审批管理")
public class ProdApprovalController {

    @Autowired
    private ProdService prodService;

    @GetMapping("/group-tree")
    @ApiOperation(value = "查询产品树")
    public R getProdTree() {
        List<ProdGroupVo> vos = prodService.getProdGroupTree();
        vos.removeIf(s -> ProductGroupEnum.DEPOSIT.getCode().equals(s.getId()));
        return R.ok(vos);
    }

    @GetMapping("/prod-list")
    @ApiOperation(value = "获取产品列表")
    public R<List<ProdEntity>> getProdList(Integer type) {
        List<ProdEntity> entities = prodService.getProdList(type);
        entities.stream().filter(s -> 3 == s.getState());
        return R.ok(entities);
    }

    @GetMapping("/prod-page")
    @ApiOperation(value = "分页获取产品列表")
    public R<IPage<ProdEntity>> getProdPage(
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer state,
            Integer type,
            Page page
    ) {
        Integer corpId = CorpContextHolder.getCorpId();
        LambdaQueryWrapper<ProdEntity> wrapper = Wrappers.<ProdEntity>lambdaQuery()
                .eq(ProdEntity::getType, type)
                .eq(ProdEntity::getCorpId, corpId);
        if (state != null && state == 0) {
            // 待审批
            wrapper.eq(ProdEntity::getState, 3);
        } else {
            List<Integer> list = new ArrayList<>();
            // 已发布
            list.add(2);
            // 已驳回
            list.add(4);
            wrapper.in(ProdEntity::getState, list);
        }
        if (code != null && !code.isEmpty())
            wrapper.like(ProdEntity::getCode, code);
        if (name != null && !name.isEmpty())
            wrapper.like(ProdEntity::getName, name);
        wrapper.orderByAsc(ProdEntity::getPrdStatus);
        wrapper.orderByAsc(ProdEntity::getCode);
        wrapper.orderByAsc(ProdEntity::getSort);
        IPage<ProdEntity> page1 = prodService.page(page, wrapper);
        return R.ok(page1);
    }

    @GetMapping
    @ApiOperation(value = "获取产品信息")
    public R getProd(Integer prodId) {
        ProdDto prodDto = prodService.getProd(prodId);
        return R.ok(prodDto);
    }

    @SysLog("产品审核")
    @PutMapping("/approval")
    @ApiOperation(value = "产品审核")
    public R approval(Integer id, String opinion, Integer state) {
        if (state != 1 && state != 2) {
            return R.failed("审批状态不在可操作范围[1-拒绝、2-同意]内");
        }
        ProdEntity entity = prodService.getById(id);
        checkEndTime(entity.getEndTime());
        if (entity.getState() != null && !entity.getState().equals(3))
            return R.failed("操作失败,您要审核的产品当前状态已非3-待审核,原因可能为发布/上架操作已被撤销");
        return R.ok(prodService.approval(entity, id, opinion, state));
    }

    private void checkEndTime(String endTimeStr) {
        if (endTimeStr == null)
            return ;
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = sdf1.parse(endTimeStr);
            long endTime = date.getTime();
            if (endTime < System.currentTimeMillis()) {
                throw new CheckedException("产品结束时间/到期日期小于当前时间，请修改后再上架/发布");
            }
        } catch(ParseException e) {
            e.printStackTrace();
        }
    }

}
